package edu.usm.roberge.client;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;

import edu.usm.roberge.server.HtmlChangedException;
import edu.usm.roberge.shared.UsgaGolfCourse;

public class GolfCourseAsyncProvider extends AsyncDataProvider<UsgaGolfCourse> {
	
	private boolean loading;
	private final GolfCourseServiceAsync golfCourseService;
	
	public GolfCourseAsyncProvider(GolfCourseServiceAsync golfCourseService) {
		this.golfCourseService = golfCourseService;
	}
	
	public void getGolfCourses(String city, String state) {
		loading = true;
		for(HasData<UsgaGolfCourse> display : getDataDisplays()) {
			display.setVisibleRangeAndClearData(new Range(0, 10), false);
		}
		
		try {
			golfCourseService.getGolfCourses(city, state, new AsyncCallback<ArrayList<UsgaGolfCourse>>() {
				@Override
				public void onFailure(Throwable caught) {
				}

				@Override
				public void onSuccess(ArrayList<UsgaGolfCourse> result) {
					updateRowData(0, result);
				}
			});
		} catch (HtmlChangedException e) {
		}
	}
	
	@Override
	protected void onRangeChanged(HasData<UsgaGolfCourse> display) {
		if (!loading) {
			updateRowCount(0, true);
		}
	}

}
